import global from '../global.json'
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)


export default new Vuex.Store({
    state: {
        LOADING: false, //全局loading
        TOKEN: '',
        USER_DATA: '', // 用户登录信息
        MENU_CONFIG:'', // 菜单配置
    },
    getters: {
        // 路由配置
        ROUTERS_CONFIG: (state) => {
            return getTmpRoute( state.USER_DATA.modules )
        },
        // 菜单配置
        MENU_CONFIG:(state => {
            return getMenu( state.USER_DATA.modules )
        })
    },
    mutations: {
        SET_USER_DATA(state, param) {
            return state.USER_DATA = param
        },
        SET_ROUTERS_CONFIG(state, param) {
            return state.ROUTERS_CONFIG = param
        }
    },
    actions: {},
    modules: {}
})

let children = []
function getTmpRoute(routes) {
    getRouterArray(routes)
    return [
        {
            "name": 'home',
            "path": '/home',
            "component": ()=> import('../views/Home'),
            "children": children
        }
    ]
}


function getRouterArray (routes) {
    for (let i in routes) {
        if (!routes.hasOwnProperty(i)) continue

        //判断节点类型
        if ( routes[i].type === 'module' ) {
            children.push( {
                "path": getResources(routes[i].name).path,
                "name": routes[i].title,
                "component" : () => import( getResources(routes[i].name).page )
            })
        }

        //如果存在子路由则动态添加
        if ( "children" in routes[i] ) {
            getRouterArray( routes[i].children )
        }
    }
}

function getMenu(menues) {
    let result = []
    for (let i in menues) {
        if (!menues.hasOwnProperty(i)) continue
        result.push({
            "title": menues[i].title,
            "path": menues[i].path,
            "name": menues[i].name,
            "ico": menues[i].ico,
            "children": getMenu(menues[i].children)
        })
    }
    return result
}

function getResources(key){
    if(key in global.resources){
        return global.resources[key]
    }else{
        return global.resources['404']
    }
}